﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;

namespace YArchitech.Revit
{
	public class SearchCurve
	{
		public SearchCurve(Element elem, XYZ point, double deviation = 0.032808398950131233)
		{
			this.element = elem;
			this.startPnt = point;
			this.searchDevision = deviation;
		}

		public bool DoSearch()
		{
			if (this.element == null)
			{
				throw new Exception("请正确构造类");
			}
			bool result;
			try
			{
				this.InitRootElement();
				result = true;
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		private void InitRootElement()
		{
			if (this.rootElement == null)
			{
				this.rootElement = new CurveElementNode(this.element, this.startPnt, this.searchDevision);
			}
			this.GetRecursiveList(this.rootElement);
		}

		private void GetRecursiveList(CurveElementNode previewElementNode)
		{
			if (previewElementNode.LineCount <= 0)
			{
				return;
			}
			CurveElement outCurveElement = previewElementNode.GetOutCurveElement();
			if (this.ElementIsExist(outCurveElement))
			{
				throw new Exception("不能进行环形搜索！");
			}
			CurveElementNode curveElementNode = new CurveElementNode(outCurveElement, previewElementNode.PointOut, this.searchDevision);
			previewElementNode.Next = curveElementNode;
			curveElementNode.PreView = previewElementNode;
			this.GetRecursiveList(curveElementNode);
			if (previewElementNode.LineCount > 1)
			{
				foreach (CurveElement curveElement in previewElementNode.SubCurveElems)
				{
					if (!curveElement.Id.IntegerValue.Equals(curveElementNode.CurveElement.Id.IntegerValue))
					{
						if (this.ElementIsExist(curveElement))
						{
							throw new Exception("不能进行环形搜索！");
						}
						CurveElementNode item = new CurveElementNode(curveElement, previewElementNode.PointOut, this.searchDevision);
						previewElementNode.SubElementNodes.Add(item);
					}
				}
				foreach (CurveElementNode curveElementNode2 in previewElementNode.SubElementNodes)
				{
					curveElementNode2.PreView = previewElementNode;
					this.GetRecursiveList(curveElementNode2);
				}
			}
		}

		private bool ElementIsExist(Element elem)
		{
			using (List<Element>.Enumerator enumerator = this.allElement.GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					if (enumerator.Current.Id == elem.Id)
					{
						return true;
					}
				}
			}
			this.allElement.Add(elem);
			return false;
		}

		public CurveElementNode GetListRoot()
		{
			return this.rootElement;
		}

		private List<Element> allElement = new List<Element>();

		private Element element;

		private CurveElementNode rootElement;

		private XYZ startPnt;

		private double searchDevision = 0.032808398950131233;
	}
}
